package com.hd.commons.shiro;

import java.util.*;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.hd.entity.sys.User;
import com.hd.service.sys.RoleService;
import com.hd.service.sys.UserService;



/**
 * @description：shiro权限认证
 */
public class ShiroDbRealm extends AuthorizingRealm {
    private static final Logger LOGGER = LogManager.getLogger(ShiroDbRealm.class);

    @Autowired private UserService userService;
    @Autowired private RoleService roleService;
    @Autowired
    private SessionDAO sessionDAO;

    public ShiroDbRealm(CacheManager cacheManager, CredentialsMatcher matcher) {
        super(cacheManager, matcher);
    }

    /**
     * Shiro登录认证(原理：用户提交 用户名和密码  --- shiro 封装令牌 ---- realm 通过用户名将密码查询返回 ---- shiro 自动去比较查询出密码和用户输入密码是否一致---- 进行登陆控制 )
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {
        LOGGER.info("Shiro开始登录认证");
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        String username=token.getUsername();
        List<User> list = userService.selectByUsername(username);
        // 账号不存在
        if (list == null || list.isEmpty()) {
            return null;
        }
        User user = list.get(0);
        //0表示 账号未启用
        if (user.getStatus() == 0) {
            return null;
        }
        // 读取用户的url和角色
        Map<String, Set<String>> resourceMap = roleService.selectResourceMapByUserId(user.getId().toString());
        Set<String> urls = resourceMap.get("urls");
        Set<String> roles = resourceMap.get("roles");
        Set<String> codes = resourceMap.get("codes");
        ShiroUser shiroUser = new ShiroUser(user.getId().toString(), user.getUsername(), user.getName(), urls);
        shiroUser.setRoles(roles);
        shiroUser.setCodeSet(codes);
        System.out.println("测试");
        LOGGER.info("pass={}",user.getPassword().toCharArray());
        LOGGER.info("salt={}", ShiroByteSource.of(user.getSalt()));
        // 认证缓存信息
        return new SimpleAuthenticationInfo(shiroUser, user.getPassword().toCharArray(),
                ShiroByteSource.of(user.getSalt()), getName());
    }

    /**
     * Shiro权限认证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(shiroUser.getRoles());
        info.addStringPermissions(shiroUser.getUrlSet());
        Set<String>urls=info.getRoles();
        Iterator<String>it=urls.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }
        return info;
    }

    /**
     * 登出清除缓存
     */
    @Override
    public void onLogout(PrincipalCollection principals) {
        super.clearCachedAuthorizationInfo(principals);
        ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
        removeUserCache(shiroUser);
    }

    /**
     * 清除用户缓存
     * @param shiroUser
     */
    public void removeUserCache(ShiroUser shiroUser){
        removeUserCache(shiroUser.getUsername());
    }

    /**
     * 清除用户缓存
     * @param
     */
    public void removeUserCache(String username){
        SimplePrincipalCollection principals = new SimplePrincipalCollection();
        principals.add(username, super.getName());
        super.clearCachedAuthenticationInfo(principals);
    }
    
    public void clearAuthz(){  
        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());  
    }  
}
